//
//  DBNoticiasDelegate.m
//  prototipo1Movies
//
//  Created by David Antonio Jiménez Xolalpa on 30/09/10.
//  Copyright 2010 ITESM - CCM. All rights reserved.
//

#import "DBNoticiasDelegate.h"
#import "Noticia.h"

@implementation DBNoticiasDelegate
@synthesize noticias;

- (id) init{
	
	databaseName = @"noticias.sqlite";
	
	// Get the path to the documents directory and append the databaseName
	NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDir = [documentPaths objectAtIndex:0];
	databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
	
	// Execute the "checkAndCreateDatabase" function
	[self checkAndCreateDatabase];
	
	// Query the database for all animal records and construct the "animals" array
	[self readNoticiasFromDatabase];
	
	NSLog(@"Noticias size: %i", [noticias count]);
	
	
	return self;
}

-(void) checkAndCreateDatabase{
	// Check if the SQL database has already been saved to the users phone, if not then copy it over
	BOOL success;
	
	// Create a FileManager object, we will use this to check the status
	// of the database and to copy it over if required
	NSFileManager *fileManager = [NSFileManager defaultManager];
	
	// Check if the database has already been created in the users filesystem
	success = [fileManager fileExistsAtPath:databasePath];
	
	NSLog(databasePath);
	NSLog(@"Succes copying: %i", success);
	
	// If the database already exists then return without doing anything
	if(success) return;
	
	// If not then proceed to copy the database from the application to the users filesystem
	
	// Get the path to the database in the application package
	NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
	
	// Copy the database from the package to the users filesystem
	[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
	
	[fileManager release];
}


-(void) readNoticiasFromDatabase {
	// Setup the database object
	sqlite3 *database;
	
	// Init the movies Array
	noticias = [[NSMutableArray alloc] init];
	
	// Open the database from the users filessytem
	if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
		NSLog(@"Connection open");
		// Setup the SQL Statement and compile it for faster access
		// This is another type of String, as of C style
		const char *sqlStatement = "select id, fecha, noticia from noticia";
		sqlite3_stmt *compiledStatement;
		int returnVal = sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL);
		if( returnVal == SQLITE_OK) {
			NSLog(@"Looping through results");
			// Loop through the results and add them to the feeds array
			while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
				// Read the data from the result row
				
				int anId = sqlite3_column_int(compiledStatement, 0);
				NSString *aFecha = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
				NSString *aNoticia = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
				
				
				// Create a new movie object with the data from the database
				Noticia *noticia = [[Noticia alloc] init];
				noticia.idNoticia = anId;
				noticia.fecha = aFecha;
				noticia.noticia = aNoticia;
				
				// Add the cafeteria object to the cafes Array
				[noticias addObject:noticia];				
				[noticia release];
			}
		} else { NSLog(@"ReturnValue: %i", returnVal); }
		// Release the compiled statement from memory
		sqlite3_finalize(compiledStatement);
		
	}
	sqlite3_close(database);	
}


@end
